<script lang="ts" setup>
import PageDialog from "@/components/PageDialog/index.vue";
import {ref, watch} from "vue";
import {OwnerEleContractObj, OwnerRentContractObj} from "@/api/demoClass";
import {
  addOwnerEle, addOwnerRent,
  ownerList,
  ownerPaymentList,
  projectList
} from "@/api/demoApi";
import {message} from "@/utils/message";
import {timeThan} from "@/utils/timeFormat";

defineOptions({
  name: "registRentDialog"
});

/**-------------------表单相关-------------------**/
//表单参数
const formData = ref({
  id: null,
  projectId:null,
  ownerId:null,
  paymentId:null,
  rentStart:null,
  rentEnd:null,
  rentCycle:null,
  rentType: null,
  rentG:null,
  rentS:null,
  privatePay:null,
  publicPay:null,
  segmentCount:null,
  segmentOnce:null,
  eleDeposit:null,
  remark:null,
  rentDeposit:null,
  status: 0
})

//表单校验
const formRules = ref({
  paymentId:[{required:true,message:'请选择付款单位',trigger:['blur','change']}],
  rentType:[{required:true,message:'请选择合约类型',trigger:['blur','change']}],
  rentStart:[
    {required:true,message:'请选择合同开始日期',trigger:['blur','change']},
    {
      validator:(rule:any,value:any,cb:any)=>{
        if(value && formData.value.rentEnd) {
          timeThan(formData.value.rentEnd,value) ? cb(new Error('结束日期不应早于开始日期')) : cb()
        }
      },
      trigger:['blur']
    }
  ],
  rentEnd:[
    {required:true,message:'请选择合同结束日期',trigger:['blur','change']},
    {
      validator:(rule:any,value:any,cb:any)=>{
        if(value && formData.value.rentStart) {
          timeThan(value,formData.value.rentStart) ? cb(new Error('结束日期不应早于开始日期')) : cb()
        }
      },
      trigger:['blur']
    }
  ],
  rentCycle:[{required:true,message:'请选择场租结算周期',trigger:['blur','change']}],
})

//项目选项
const projectOptions = ref([])
const ownerOptions = ref([])
const paymentOptions = ref([])
const cycleOptions = [
  {value:0,label:'一年一付',divisor:1},
  {value:1,label:'两年一付',divisor:2},
  {value:2,label:'三年一付',divisor:3},
  {value:3,label:'五年一付',divisor:5},
  {value:4,label:'十年一付',divisor:10},
  {value:5,label:'一次付清',divisor:100},
]
const typeOptions = [
  {value:0,label:'租金G'},
  {value:1,label:'租金S'},
  {value:2,label:'对私处理'},
  {value:3,label:'对公处理'},
  {value:4,label:'保证金'},
]
const segmentOptions = [
  {value:0,label:'一年分摊',divisor:1},
  {value:1,label:'两年分摊',divisor:2},
  {value:2,label:'三年分摊',divisor:3},
  {value:3,label:'四年分摊',divisor:4},
  {value:4,label:'五年分摊',divisor:5},
]
const getProjectOptions = ()=>{
  projectOptions.value = projectList().map(item=>({value:item.id,label:`${item.projectNo}(${item.projectName})`}))
}
const getOwnerOptions = ()=>{
  ownerOptions.value = ownerList().map(item=>({value:item.id,label:item.ownerName}))
}
const getPaymentOptions = id =>{
  paymentOptions.value = ownerPaymentList(id).map(item=>({value:item.id,label:`${item.paymentName}(${item.account})`}))
}

/**-------------------打开弹框-------------------**/
//标题
const dialogTitle = ref('')
const dialog = ref()
//弹框显示
const dialogShow = (title: string,data?: object)=>{
  dialogTitle.value = title
  if(data) {
    if(title ==='查看') {
      formData.value = {...data}
    }else {
      formData.value.projectId = data.projectId
      formData.value.ownerId = data.ownerId
    }
  }
  getProjectOptions()
  getOwnerOptions()
  getPaymentOptions(data.ownerId)
  dialog.value.dialogVisible = true
}
defineExpose({
  dialogShow
})

/**-------------------事件回调-------------------**/
//选择类型
const selectType = (val)=>{
  formData.value.rentG = null
  formData.value.rentS = null
  formData.value.privatePay = null
  formData.value.publicPay = null
  formData.value.rentCycle = null
  formData.value.rentG = null
  formData.value.segmentCount = null
  formData.value.segmentOnce = null
  formData.value.eleDeposit = null
  formData.value.rentDeposit = null
  if([2,3,4].includes(val)){
    formData.value.rentCycle = 5  //一次付清
  }
}
//分摊年数选择
const inputPay = ()=>{
  if(!formData.value.privatePay && !formData.value.publicPay) return
  if(formData.value.rentType === 2 && !formData.value.segmentOnce) return
  if(formData.value.rentType === 3 && !formData.value.segmentOnce) return
  const divisor = segmentOptions.filter(item=>item.value === val)[0].divisor ?? null
  if(divisor) {
    formData.value.segmentOnce = formData.value.rentType === 2 ? (formData.value.privatePay / divisor) : (formData.value.publicPay / divisor)
  }
}
const selectCount = (val)=>{
  if(formData.value.rentType === 2 && !formData.value.privatePay) return
  if(formData.value.rentType === 3 && !formData.value.publicPay) return
  const divisor = segmentOptions.filter(item=>item.value === val)[0].divisor ?? null
  if(divisor) {
    formData.value.segmentOnce = formData.value.rentType === 2 ? (formData.value.privatePay / divisor) : (formData.value.publicPay / divisor)
  }
}
//取消
const form = ref()
const handlerCancel = ()=> new Promise(async (resolve,reject)=>{
  try{
    await form.value.resetFields()
    formData.value = {
      id: null,
      projectId:null,
      ownerId:null,
      paymentId:null,
      rentStart:null,
      rentEnd:null,
      rentCycle:null,
      rentType: null,
      rentG:null,
      rentS:null,
      privatePay:null,
      publicPay:null,
      segmentCount:null,
      segmentOnce:null,
      eleDeposit:null,
      rentDeposit:null,
      remark:null,
      status: 0
    }
    dialog.value.dialogVisible = false
    resolve({})
  }catch(e){
    console.log(e)
    reject(e)
  }
})
//确认
const emits = defineEmits(['done'])
const handlerConfirm = ()=> new Promise(async (resolve,reject)=>{
  try{
    await form.value.validate()
    //todo 新增、编辑接口
    const newOwnerEle = new OwnerRentContractObj(formData.value)
    const result = addOwnerRent(newOwnerEle)
    if(!result) {
      message("添加成功", { type: "success" });
      await handlerCancel()
      emits('done')
      resolve({})
    }else {
      message(result, { type: "warning" });
      resolve({})
    }
  }catch(e){
    reject(e)
  }
})
</script>

<template>
  <PageDialog ref="dialog" :handler-cancel="handlerCancel" :handler-confirm="handlerConfirm" :title="dialogTitle">
    <el-form ref="form" :disabled="dialogTitle === '查看'" :model="formData" :rules="formRules" label-position="top" label-width="auto">
      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="formData.projectId" clearable disabled filterable placeholder="请选择项目名称">
          <el-option v-for="(item,index) in projectOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属业主" prop="ownerId">
        <el-select v-model="formData.ownerId" clearable disabled filterable placeholder="请选择所属业主">
          <el-option v-for="(item,index) in ownerOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="付款单位" prop="paymentId">
        <el-select v-model="formData.paymentId" clearable filterable placeholder="请选择付款单位">
          <el-option v-for="(item,index) in paymentOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="合约类型" prop="rentType">
        <el-select v-model="formData.rentType" clearable filterable placeholder="请选择合约类型" @change="selectType">
          <el-option v-for="(item,index) in typeOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="起始日期" prop="rentStart">
        <el-date-picker
          v-model="formData.rentStart"
          clearable
          format="YYYY-MM-DD"
          placeholder="请选择合约起始日期"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="rentEnd">
        <el-date-picker
          v-model="formData.rentEnd"
          clearable
          format="YYYY-MM-DD"
          placeholder="请选择合约结束日期"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结算周期" prop="rentCycle">
        <el-select v-model="formData.rentCycle" :disabled="[2,3,4].includes(formData.rentType)" clearable filterable placeholder="请选择场租结算周期">
          <el-option v-for="(item,index) in cycleOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.rentType === 0" label="租金G(元)" prop="rentG">
        <el-input-number v-model.number="formData.rentG" :controls="false" :precision="2" :step="0.01" placeholder="请输入租金G(元)/每年"/>
      </el-form-item>
      <el-form-item v-if="formData.rentType === 1" label="租金S" prop="rentS">
        <el-input-number v-model.number="formData.rentS" :controls="false" :precision="2" :step="0.01" placeholder="请输入租金S(元)/每年"/>
      </el-form-item>
      <el-form-item v-if="formData.rentType === 2" label="对私处理(元)" prop="privatePay">
        <el-input-number v-model.number="formData.privatePay" :controls="false" :precision="2" :step="0.01" placeholder="请输入对私处理(元),非金额需折算" @blur="inputPay"/>
      </el-form-item>
      <el-form-item v-if="formData.rentType === 3" label="对公处理(元)" prop="publicPay">
        <el-input-number v-model.number="formData.publicPay" :controls="false" :precision="2" :step="0.01" placeholder="请输入对公处理(元),非金额需折算" @blur="inputPay"/>
      </el-form-item>
      <el-form-item v-if="[2,3].includes(formData.rentType)" label="分摊年数" prop="segmentCount">
        <el-select v-model="formData.segmentCount" :disabled="!formData.privatePay && !formData.publicPay" clearable filterable placeholder="请选择分摊年数" @change="selectCount">
          <el-option v-for="(item,index) in segmentOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="[2,3].includes(formData.rentType)" label="年均分摊(元)" prop="segmentOnce">
        <el-input-number v-model.number="formData.segmentOnce" :controls="false" :precision="2" :step="0.01" disabled placeholder="根据分摊年数自动计算"/>
      </el-form-item>
      <el-form-item v-if="formData.rentType === 4" label="电费保证金(元)" prop="eleDeposit">
        <el-input-number v-model.number="formData.eleDeposit" :controls="false" :precision="2" :step="0.01" placeholder="请输入电费保证金(元)"/>
      </el-form-item>
      <el-form-item v-if="formData.rentType === 4" label="场租保证金(元)" prop="rentDeposit">
        <el-input-number v-model.number="formData.rentDeposit" :controls="false" :precision="2" :step="0.01" placeholder="请输入场租保证金(元)"/>
      </el-form-item>
      <el-form-item label="备注" prop="company">
        <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
      </el-form-item>
    </el-form>
  </PageDialog>
</template>

<style lang="scss" scoped>
:deep(.el-form) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;

  .el-form-item {
    width: 48%;

    .el-input,
    .el-input-number,
    .el-date-picker,
    .el-select {
      width: 100%;
    }
  }
}
</style>
